//
//  ThirdViewControllerOfFamous.m
//  FloatClouds
//
//  Created by 黄威 on 16/8/30.
//  Copyright © 2016年 黄威. All rights reserved.
//

#import "ThirdViewControllerOfFamous.h"
#import "RankTableViewBaseCell.h"
#import "BaseButton.h"
#import "TAMacro.h"
#import "HWLNetworkTool.h"
#import "Rank0.h"
#import "Rank0Cigarettes.h"
#import "UIImageView+WebCache.h"
#import "RankTableviewSecondCell.h"
#import "Rank1.h"
#import "Rank1Cigarettes.h"
#import "MJRefresh.h"
#import "ProductDetailTableViewController.h"
#import "SVProgressHUD.h"

@interface ThirdViewControllerOfFamous ()
@property (nonatomic, retain) UIScrollView *viewOfHeader;
@property (nonatomic, retain) NSMutableArray *arrayOfButton;
@property (nonatomic, retain) Rank0 *rank;
@property (nonatomic, retain) Rank1 *rank1;
@property (nonatomic, assign) NSInteger type;
@property (nonatomic, assign) NSInteger btnTag;
@property (nonatomic, assign) NSInteger btnTag2;


@end

@implementation ThirdViewControllerOfFamous

- (void)viewWillAppear:(BOOL)animated{

    self.tabBarController.tabBar.hidden = NO;

}

- (void)viewDidLoad {
    [super viewDidLoad];
  
    [self createHeaderView];
    [self.tableView registerClass:[RankTableViewBaseCell class] forCellReuseIdentifier:@"RankTableViewBaseCell"];
    [self.tableView registerClass:[RankTableviewSecondCell class] forCellReuseIdentifier:@"RankTableviewSecondCell"];
  
    [self handleData];
    
    __weak typeof(self) weakSelf = self;
    //默认block方法：设置下拉刷新
    self.tableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        [weakSelf refreshData];
    }];
    self.type = 0;
  
    self.btnTag2 = 10000;
}


- (void)handleData{

    /*
     
     sn=0&type=1
     */
    
    NSString *dicOfBody = @"sn=0&type=0";
    NSDictionary *dicOfHeader = @{@"Content-Type":@"application/x-www-form-urlencoded"};
    
    [HWLNetworkTool POST:@"http://app.yanyue.cn/index/rank" andBody:dicOfBody andBodyStyle:HWLBodyString andHeader:dicOfHeader andResponse:HWLJSON andSuccessBlock:^(id result) {
        
        self.rank = [Rank0 modelWithDic:result];
        [self.tableView reloadData];
           } andFailureBlock:^(NSError *error) {
        
    }];

}

- (void)createHeaderView{

    self.arrayOfButton = [NSMutableArray array];
    
    self.viewOfHeader = [[UIScrollView alloc]init];
    self.viewOfHeader.frame = CGRectMake(0, 0,SCREEN_SIZE_WIDTH_ME , 35);
    self.viewOfHeader.contentSize = CGSizeMake(SCREEN_SIZE_WIDTH_ME * 1.5, 35);
    self.viewOfHeader.showsHorizontalScrollIndicator = NO;
    NSUserDefaults *nightIsOn = [NSUserDefaults standardUserDefaults];
    NSString *isOn = [nightIsOn objectForKey:@"night"];
    
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(ON)
                                                 name:@"NIGHTON"
                                               object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(OFF)
                                                 name:@"NIGHTOFF"
                                               object:nil];
  
    
    if ([isOn isEqualToString:@"0"]) {
        
        self.viewOfHeader.backgroundColor = [UIColor whiteColor];
        
        
        
    }else if([isOn isEqualToString:@"1"]){
        
        self.viewOfHeader.backgroundColor = [UIColor colorWithRed:93/255.0 green:92/255.0 blue:101/255.0 alpha:1];
        
    }

    
    
    
    
     NSArray *arrayOfRankTitle = @[@"本月关注",@"低焦风云",@"性价比拼",@"口味得分",@"外观得分"];
    
    for (int i = 10000; i < 10005; i++) {
        
        BaseButton *button = [BaseButton buttonWithType:UIButtonTypeCustom];
        button.frame = CGRectMake(SCREEN_SIZE_WIDTH_ME * 0.3 * (i - 10000), 0, (SCREEN_SIZE_WIDTH_ME  * 0.3), 30);
        button.tag = i;
        [self.viewOfHeader addSubview:button];
        [self.arrayOfButton addObject:button];
      
        [button setTitle:arrayOfRankTitle[i - 10000] forState:UIControlStateNormal];
        [button setTitleColor:[UIColor grayColor] forState:UIControlStateNormal];
        [button addTarget:self action:@selector(buttonOfData:) forControlEvents:UIControlEventTouchUpInside];
        
    }

    
    BaseButton *button = [self.viewOfHeader viewWithTag:10000];
    [button setTitleColor:[UIColor colorWithRed:18.0 / 255 green:86.0 / 255 blue:138.0 / 255 alpha:1] forState:UIControlStateNormal];
    
    
}

- (void)buttonOfData:(BaseButton *)button{
    
    for (BaseButton *btn in _arrayOfButton){
        if (btn.tag ==button.tag) {
            [btn setTitleColor:[UIColor colorWithRed:18.0 / 255 green:86.0 / 255 blue:138.0 / 255 alpha:1] forState:UIControlStateNormal];
        } else {
            [btn setTitleColor:[UIColor grayColor] forState:UIControlStateNormal];
        }
    }
    
    switch (button.tag) {
        case 10000:
            
        { self.type = 0;
            self.rank1 = nil;
            [self refreshData];
            break;
        }
        case 10001:
        {
            
            self.type = 1;
            self.rank = nil;
            [self refreshData];
        }
            break;
            
        case 10002:{
            self.type = 2;
            self.rank = nil;
            [self refreshData];
        }
            
            break;
            
        case 10003:{
             self.type = 3;
             self.rank = nil;
            [self refreshData];
           
}
            
            break;
            
        case 10004:{
    
            self.type = 4;
            self.rank = nil;
            [self refreshData];
            
        }
          break;
     
        default:
            
            break;
    }

}



- (void)refreshData{
 
    
    [SVProgressHUD show];
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        // time-consuming task
        dispatch_async(dispatch_get_main_queue(), ^{
            
            
            [SVProgressHUD showWithStatus:@"加载中..."];
            [SVProgressHUD setDefaultMaskType:SVProgressHUDMaskTypeClear];
            [SVProgressHUD setMinimumDismissTimeInterval:5];
            
            
            
        });
    });
    
    
   
    
    NSString *dicOfBody = [@"sn=0&type="stringByAppendingString:[NSString stringWithFormat:@"%lu",self.type ]];
    
    NSDictionary *dicOfHeader = @{@"Content-Type":@"application/x-www-form-urlencoded"};
    
    [HWLNetworkTool POST:@"http://app.yanyue.cn/index/rank" andBody:dicOfBody andBodyStyle:HWLBodyString andHeader:dicOfHeader andResponse:HWLJSON andSuccessBlock:^(id result) {
        self.rank1 = [Rank1 modelWithDic:result];
        self.rank = nil;
       
        [self.tableView reloadData];
        [self.tableView.mj_header endRefreshing];
        [SVProgressHUD dismiss];
        
    } andFailureBlock:^(NSError *error) {
        
    }];

}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{


    if (self.rank) {
        return self.rank.cigarettes.count;
    }
    if (self.rank1) {
        return self.rank1.cigarettes.count;
    }
    return 0;
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{

    if (section == 0) {
 
        return self.viewOfHeader;
 
    }


    return nil;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{

    return 35;

}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{

    if (self.rank) {
        
        RankTableViewBaseCell *cell = [self.tableView dequeueReusableCellWithIdentifier:@"RankTableViewBaseCell"];
        
        NSInteger a = indexPath.row;
        NSString *str2 = [NSString stringWithFormat:@"%lu",a+1];
        [cell.diandian setTitle:str2 forState:UIControlStateNormal];
        cell.name.text = self.rank.cigarettes[indexPath.row].name;
        NSURL *url = [NSURL URLWithString:self.rank.cigarettes[indexPath.row].photo];
        [cell.imageViewLift sd_setImageWithURL:url placeholderImage:[UIImage imageNamed:@"placeholder"]];
        cell.catrameinput.text = self.rank.cigarettes[indexPath.row].catrame;
        cell.priceinput.text = self.rank.cigarettes[indexPath.row].price;
        cell.numberOfLike.text = self.rank.cigarettes[indexPath.row].score;
        
        return cell;
        
        
    }
    if (self.rank1) {
        
        RankTableviewSecondCell *cell = [self.tableView dequeueReusableCellWithIdentifier:@"RankTableviewSecondCell"];
        NSInteger a = indexPath.row;
        NSString *str2 = [NSString stringWithFormat:@"%lu",a+1];
        [cell.diandian setTitle:str2 forState:UIControlStateNormal];
        cell.name.text = self.rank1.cigarettes[indexPath.row].name;
        NSURL *url = [NSURL URLWithString:self.rank1.cigarettes[indexPath.row].photo];
        [cell.imageViewLift sd_setImageWithURL:url placeholderImage:[UIImage imageNamed:@"placeholder"]];
        cell.catrameinput.text = self.rank1.cigarettes[indexPath.row].catrame;
        cell.priceinput.text = self.rank1.cigarettes[indexPath.row].price;
        NSInteger integer = self.rank1.cigarettes[indexPath.row].score;
        NSString *str = [NSString stringWithFormat:@"%ld",integer];
        cell.numberOfLike.text = str;
        return cell;
    }
    
    
    return nil;

}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{


    return 120;

}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{

    ProductDetailTableViewController *productDetail = [[ProductDetailTableViewController alloc]init];

    
    if (self.rank) {
        
        productDetail.productId = self.rank.cigarettes[indexPath.row].uid;
    }
    if (self.rank1) {
        productDetail.productId = self.rank1.cigarettes[indexPath.row].uid;
    }
   
    [self.navigationController pushViewController:productDetail animated:YES];

}

// 去掉UItableview headerview黏性(sticky)
- (void)scrollViewDidScroll:(UIScrollView *)scrollView
{
    CGFloat sectionHeaderHeight = 35;
    if (scrollView.contentOffset.y<=sectionHeaderHeight&&scrollView.contentOffset.y>=0) {
        scrollView.contentInset = UIEdgeInsetsMake(-scrollView.contentOffset.y, 0, 0, 0);
    }
    else if (scrollView.contentOffset.y>=sectionHeaderHeight) {
        scrollView.contentInset = UIEdgeInsetsMake(-sectionHeaderHeight, 0, 0, 0);
    }
}

- (void)ON{
    
    self.viewOfHeader.backgroundColor =  [UIColor colorWithRed:93/255.0 green:92/255.0 blue:101/255.0 alpha:1];
    
    
}

- (void)OFF{
    //lanse
    self.viewOfHeader.backgroundColor =[UIColor whiteColor];
    
    
}
- (void)dealloc{
    
    
    [[NSNotificationCenter defaultCenter] removeObserver:self name:@"NIGHTON" object:nil];
    [[NSNotificationCenter defaultCenter] removeObserver:self name:@"NIGHTOFF"object:nil];
    
    
}
@end
